package db_java;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//TODO Company insert
//TODO get Client & get Company
//TODO close connection
//TODO delete unused methods

public class DBConnect {
	//get client company="company name" firstName="" lastName=''
	//put client company='' firstName='' lastName=''
	//list client
	//list company
	public static void main(String[] args) throws SQLException {
		Connection connection = getConnection();
		try{
			commandExecute(connection, args);
		}
		finally {
			connection.close();
		}
	}
	

	public static void commandExecute(Connection connection, String[] args) throws SQLException {
		List<String> list = Arrays.asList(args);
		Object o = parseEntry(list.get(1), list.subList(2, list.size()));
		Dao dao = getDao(list.get(1), connection);
		Command command = getCommand(list.get(0));
		command.execute(dao, o);
	}


	private static Command getCommand(String string) {
		if (string.equals("put")){
			return new CommandPut();
		}
		if (string.equals("get")){
			return new CommandGet();
		}
		if (string.equals("list")){
			return new CommandList();
		}
		throw new RuntimeException();
	}

	private static Connection getConnection() throws SQLException {
		Connection connection = DriverManager.getConnection(
				"jdbc:oracle:thin:@localhost:1522:orajava", 
				"forjava",
				"forjava123");
		return connection;
	}

	private static Dao getDao(String string, Connection connect) {
		if (string.equals("client")){
			return new PersonDao(connect, new CompanyDao(connect));
		}
		if (string.equals("company")){
			return new CompanyDao(connect);
		} 
		throw new RuntimeException("Choose client or company");
	}

	private static Object parseEntry(String entryName, List<String> parameters) {
		Map<String, String> map = parse(parameters);
//		for (String m: map.keySet()){
//			System.out.println(map.get(m));
//		}
		if (entryName.equals("client")){
			Person client = new Person(map.get("firstName"), map.get("lastName"), new Company(map.get("company"), null, null));
			return client;
		} 
		if (entryName.equals("company")){
			Company company = new Company(map.get("company"), map.get("companyAdd"), null);
			return company;
		} 
		throw new RuntimeException("Choose client or company");		
	}

	private static Map<String, String> parse(List<String> parameters) {
		Map<String, String> result = new HashMap<String, String>();
		for (String s: parameters) {
			String[] arr = s.split("=");
			result.put(arr[0], arr[1]);
		}
		return result;
	}
}

